package com.guet.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.guet.DTO.CommentAddDTO;
import com.guet.DTO.CommentDTO;
import com.guet.DTO.TopicDeleteReasonDTO;
import com.guet.DTO.TopicSaveDTO;
import com.guet.Entity.Comment;
import com.guet.Entity.DeleteTopicAndReply;
import com.guet.Entity.TemplateTopic;
import com.guet.Entity.Topic;
import com.guet.VO.CommentVO;
import com.guet.VO.DeleteTopicAndReplyVO;
import com.guet.VO.TemplateTopicVO;
import com.guet.VO.TopicVO;
import com.guet.constant.PageConstant;
import com.guet.context.BaseContext;
import com.guet.mapper.DeleteTopicAndReplyMapper;
import com.guet.mapper.TopicMapper;
import com.guet.service.TopicService;
import com.guet.result.UnfinityPageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class TopicServiceImpl implements TopicService {
    @Autowired
    private TopicMapper topicMapper;
    @Autowired
    private DeleteTopicAndReplyMapper deleteTopicAndReplyMapper;


    /**
     * 根据类型获取话题列表
     *
     * @param type
     * @return
     */
    @Override
    public List<TopicVO> list(String type) {
        List<TopicVO> list = topicMapper.list(type);
        for (TopicVO topicVO : list) {
            Integer id = topicVO.getId();
            Integer replyCount = topicMapper.getReplyCount(id);
            topicVO.setReply(replyCount);
        }
        return list;
    }

    /**
     * 根据id获取话题
     *
     * @param id
     * @return
     */
    @Override
    public TopicVO getTopicDetail(String id) {
        return topicMapper.queryById(id);
    }

    /**
     * 通过topic获取评论
     *
     * @param commentDTO
     * @return
     */
    @Override
    public UnfinityPageResult getCommentList(CommentDTO commentDTO) {
        PageHelper.startPage(commentDTO.getCurrentPage(), PageConstant.PAGE_SIZE);
        Page<CommentVO> result = topicMapper.getCommentList(commentDTO);
        Long total = result.getTotal();
        List<CommentVO> list = result.getResult();
        return new UnfinityPageResult(total, list, commentDTO.getCurrentPage());
    }

    /**
     * 添加评论
     *
     * @param commentAddDTO
     */
    @Override
    public void addComment(CommentAddDTO commentAddDTO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddDTO, comment);
        comment.setPublisherId(BaseContext.getCurrentId());
        comment.setCreateTime(LocalDateTime.now());
        topicMapper.add(comment);
    }

    /**
     * 更新话题草稿
     *
     * @param topicSaveDTO
     */
    @Override
    public void save(TopicSaveDTO topicSaveDTO) {
        // 获取当前用户的ID
        Long userId = BaseContext.getCurrentId();

        // 查找当前用户的草稿
        TemplateTopic existingDraft = topicMapper.queryDraftByUserId(userId);

        TemplateTopic draft = new TemplateTopic();
        BeanUtils.copyProperties(topicSaveDTO, draft);
        draft.setUserId(userId);

        if (existingDraft == null) {
            // 没有草稿，第一次保存
            draft.setCreateTime(LocalDateTime.now());
            topicMapper.save(draft);
        } else {
            // 有草稿，保留原创建时间并更新
            draft.setCreateTime(existingDraft.getCreateTime());
            draft.setUpdateTime(LocalDateTime.now());
            topicMapper.deleteDraftByUserId(userId); // 删除原草稿
            topicMapper.save(draft); // 保存新草稿
        }
    }

    /**
     * 获取话题草稿
     *
     * @return
     */
    @Override
    public TemplateTopicVO getDraft() {
        Long userId = BaseContext.getCurrentId();
        TemplateTopic templateTopic = topicMapper.queryDraftByUserId(userId);
        if (templateTopic == null) {
            return new TemplateTopicVO(); // 返回一个空对象
            // 或者：
            // throw new CustomException("未找到草稿记录");
        }

        TemplateTopicVO templateTopicVO = new TemplateTopicVO();
        BeanUtils.copyProperties(templateTopic, templateTopicVO);
        return templateTopicVO;
    }


    /**
     * 发布话题
     *
     * @param topicSaveDTO
     */
    @Override
    public void publish(TopicSaveDTO topicSaveDTO) {
        // 删除草稿
        Long userId = BaseContext.getCurrentId();
        topicMapper.deleteDraftByUserId(userId);
        Topic topic = new Topic();
        BeanUtils.copyProperties(topicSaveDTO, topic);
        topic.setPublisherId(userId);
        topic.setCreateTime(LocalDateTime.now());
        topic.setWatch(0);
        topic.setReplyCount(0);
        topicMapper.insert(topic);
    }

    /**
     * 删除评论
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteTopicById(String id) {
        // 删除话题和他下面的评论
        topicMapper.deleteTopicById(id);
        topicMapper.deleteCommentByTopicId(id);
    }

    /**
     * 删除评论
     *
     * @param id
     */
    @Override
    public void deleteCommentById(String id) {
        topicMapper.deleteCommentById(id);
    }

    /**
     * 删除话题并告知学生原因
     *
     * @param topicDeleteReasonDTO
     */
    @Override
    public void askReasonTopic(TopicDeleteReasonDTO topicDeleteReasonDTO) {
        Topic topic = topicMapper.selectTopic(topicDeleteReasonDTO.getId());
        String reason = !Objects.equals(topicDeleteReasonDTO.getReason(), "其他") ?
                topicDeleteReasonDTO.getReason() : topicDeleteReasonDTO.getAnotherReason();
        DeleteTopicAndReply deleteTopicAndReply = DeleteTopicAndReply.builder()
                .userId(topic.getPublisherId())
                .title(topic.getTitle())
                .content(topic.getContent())
                .createTime(LocalDateTime.now())
                .reason(reason)
                .topicPublishTime(topic.getCreateTime())
                .build();
        deleteTopicAndReplyMapper.insertTopicReason(deleteTopicAndReply);
    }

    /**
     * 获取违规信息
     *
     * @return
     */
    @Override
    public List<DeleteTopicAndReplyVO> getIllegalTopicList() {
        Long userId = BaseContext.getCurrentId();
        return deleteTopicAndReplyMapper.list(userId);
    }

    @Override
    public void askReasonComment(TopicDeleteReasonDTO topicDeleteReasonDTO) {
        String reason = !Objects.equals(topicDeleteReasonDTO.getReason(), "其他") ?
                topicDeleteReasonDTO.getReason() : topicDeleteReasonDTO.getAnotherReason();
        Comment comment = topicMapper.getCommentById(topicDeleteReasonDTO.getId());
        DeleteTopicAndReply deleteTopicAndReply = DeleteTopicAndReply.builder()
                .userId(comment.getPublisherId())
                .title(comment.getContent())
                .content(comment.getContent())
                .createTime(LocalDateTime.now())
                .reason(reason)
                .topicPublishTime(comment.getCreateTime())
                .build();
        deleteTopicAndReplyMapper.insertTopicReason(deleteTopicAndReply);
    }
}
